/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.widget;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

public abstract class ListViewAdapter<T> extends ArrayAdapter<T> {

    protected Activity activity;
    private int viewResourceId;

    protected LayoutInflater inflater;
    
    public ListViewAdapter(Context context, int viewResourceId) {
        this((Activity) context, viewResourceId);
    }

    public ListViewAdapter(Activity activity, int viewResourceId) {
        super(activity, 0);

        this.activity = activity;
        this.viewResourceId = viewResourceId;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        // adapter caches views. So reinflate,
        // if cached view is not instance of ViewGroup
        if (convertView == null || !(convertView instanceof ViewGroup)) {
            convertView = inflater.inflate(viewResourceId, null);
        }

        return doGetView(position, convertView, parent);
    }

    /**
     * Resolves a child view and caches it.
     * Calls {@link View#findViewById(int)} on the provided <code>view</code>, and stores the result as a tag in that <code>view</code>. 
     * 
     * @param view
     * @param id
     * @return View with the given id, or null if that view was not found
     * @see View#findViewById(int)
     * @see View#setTag(int, Object)
     */
    protected View findViewById(View view, int id) {
        Object tag = view.getTag(id);
        
        if (tag == null) {
            tag = view.findViewById(id);
            view.setTag(id, tag);
        }
        
        return (View) tag;
    }

    protected abstract View doGetView(int position, View view, ViewGroup parent);
}
